package com.gw.vip.server.service;

import com.gw.vip.common.exception.ExceptionEnums;
import com.gw.vip.common.exception.ServiceException;
import com.gw.vip.server.bo.IssuInfo;
import com.gw.vip.server.constants.SysArgKey;
import com.gw.vip.server.dto.UserInfoByCodeDto;
import com.gw.vip.server.platform.vipcenter.VipCenterService;
import com.gw.vip.server.platform.vipcenter.dto.VipCenterUserInfoByCodeDto;
import com.gw.vip.server.platform.vipcenter.vo.VipCenterUserInfoByCodeVo;
import com.gw.vip.server.po.UserInfo;
import com.gw.vip.server.service.dao_service.SysArgService;
import com.gw.vip.server.service.dao_service.UserInfoService;
import com.gw.vip.server.vo.UserInfoByCodeVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author GW
 * @description
 * @since 2022-04-25
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthBiz {
    private final VipCenterService vipCenterService;
    private final UserInfoService userInfoService;
    private final SysArgService sysArgService;

    public UserInfoByCodeVo userInfoByCode(UserInfoByCodeDto dto) {
        VipCenterUserInfoByCodeDto vipCenterUserInfoByCodeDto = new VipCenterUserInfoByCodeDto();
        vipCenterUserInfoByCodeDto.setRandomCode(dto.getRandomCode());
        IssuInfo issuInfo = sysArgService.getObject(SysArgKey.ISSU_INFO, IssuInfo.class);
        if (issuInfo==null){
            log.error("发行机构不存在！");
            throw new ServiceException(ExceptionEnums.ISSU_NOT_EXIST);
        }
        vipCenterUserInfoByCodeDto.setIssuId(issuInfo.getId());
        VipCenterUserInfoByCodeVo vipCenterUserInfoByCodeVo = vipCenterService.userInfoByCode(vipCenterUserInfoByCodeDto);

        UserInfo userInfo = userInfoService.getById(vipCenterUserInfoByCodeVo.getId());
        if (userInfo==null){
            //将用户信息保存到本地
            userInfo = new UserInfo();
            BeanUtils.copyProperties(vipCenterUserInfoByCodeVo, userInfo);
            userInfoService.save(userInfo);
        }

        UserInfoByCodeVo vo = new UserInfoByCodeVo();
        BeanUtils.copyProperties(vipCenterUserInfoByCodeVo, vo);
        return vo;
    }
}
